package com.run_java_test.t.test_run;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

@Component
public class DynamicControllerRemover {

    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 动态移除 Controller 和映射
     *
     * @param beanName 要移除的 Controller Bean 名称
     */
    public void removeController(String beanName) {
        try {
            // 获取 RequestMappingHandlerMapping
            RequestMappingHandlerMapping handlerMapping =
                    applicationContext.getBean(RequestMappingHandlerMapping.class);

            // 通过 Bean 名称找到对应的 Controller 映射
            Object controller = applicationContext.getBean(beanName);

            if (controller != null) {
                handlerMapping.getHandlerMethods().forEach((mapping, method) -> {
                    if (method.getBean().equals(controller)) {
                        // 注销对应的 URL 映射
                        handlerMapping.unregisterMapping(mapping);
                    }
                });

                // 从容器中移除 Bean
                BeanDefinitionRegistry beanDefinitionRegistry =
                        (BeanDefinitionRegistry) applicationContext.getAutowireCapableBeanFactory();
                beanDefinitionRegistry.removeBeanDefinition(beanName);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
